import React from 'react';
import axios from 'axios';
import {Button, Form, Select, Table, DatePicker} from 'antd';
import YearSelect from '../../components/select/yearSelect'
import MonthSelect from '../../components/select/monthSelect'
import asyncComponent from '../../components/echats/AsyncComponent';
import {injectIntl} from 'react-intl';
import {sessionManager} from "../../utils/sessionStorage";
import qs from "qs";

const {Column} = Table;
const Option = Select.Option;
const LineReact = asyncComponent(() => import(/* webpackChunkName: "LineReact" */'../../components/echats/LineReact'))  //折线图组件
const {RangePicker} = DatePicker;

@Form.create()
class CarChargeReport extends React.Component {
    constructor(props) {
        super(props);
        this.marginStyle = {
            marginRight: 20
        };
        this.selectStyle = {
            float: 'left'
        }
        this.state = {
            showForm: '1',
            dateType: '1',
            dateTypeCopy: '1',
            tableData: [],
            date4: [],
            year: this.getYear(),
            month: this.getMonth(),
            selectUrl: '/report/departMent',
            refresh: 0,
            lineOption: {
                title: {
                    text: '折线图堆叠'
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {},
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '3%',
                    containLabel: true
                },
                toolbox: {
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
                },
                yAxis: {
                    name: this.props.intl.messages.common.unitsDegree,
                    type: 'value'
                },
                series: []
            }
        }
    }

    selectValue = (value) => {
        console.log(`selected ${value}`);
        this.setState({
            dateType: value
        })
    };

    handleChange = (value) => {
        this.setState({
            showForm: value
        })
    }

    getMonth() {
        let myDate = new Date();
        let month = myDate.getMonth() + 1;
        return month;
    }


    getYear() {
        let myDate = new Date();
        let year = myDate.getFullYear();
        return year;
    }


    changeYear(value) {
        this.setState({
            year: value
        })
    }

    changeMonth(value) {
        this.setState({
            month: value
        })
    }

    onChange = (date, dateString) => {
        console.log(date, dateString);
        this.setState({
            date4: dateString
        })
    }

    search = () => {
        let value = {
            dateType: this.state.dateType
        };
        if (this.state.dateType === '1') {
            value.date = this.state.year
        }
        if (this.state.dateType === '2') {
            value.date = `${this.state.year}-${this.state.month < 10 ? '0' + this.state.month : this.state.month}`
        }

        if (this.state.dateType === '4') {
            value.startDate = this.state.date4[0];
            value.endDate = this.state.date4[1];
        }

        this.setState({
            params:value
        });

        axios.post('/api/statistics/car/charge/qry', {
            ...value
        }).then(res => {
            console.log(res);
            if (res && res.data) {
                this.setState({
                    tableData: res.data,
                    dateTypeCopy: this.state.dateType
                });
                //开始组建折线图信息
                let seriesArr = new Array();
                let nameArr = new Array();
                this.setState(Object.assign(this.state.lineOption, {
                    xAxis: {
                        type: 'category',
                        boundaryGap: false,
                        data: res.data[0].dateList
                    },
                }));

                for (let i = 0; i < res.data.length; i++) {
                    let jsonObj = {};
                    nameArr.push(res.data[i].plateNo);
                    jsonObj['name'] = res.data[i].plateNo;
                    jsonObj['type'] = 'line';
                    jsonObj['smooth'] = true;
                    jsonObj['data'] = res.data[i].data;
                    seriesArr.push(jsonObj);
                }

                if (nameArr.length > 0) {
                    this.setState(Object.assign(this.state.lineOption, {legend: {'data': nameArr}, series: seriesArr}));
                }
                else {
                    let jsonObj = {};
                    jsonObj['name'] = '';
                    jsonObj['type'] = 'line';
                    jsonObj['smooth'] = true;
                    jsonObj['data'] = [];
                    seriesArr.push(jsonObj);
                    this.setState(Object.assign(this.state.lineOption, {series: seriesArr}));
                }
            }
        });
    }


    componentWillMount() {
        let value={
            date: this.state.year,
            dateType: this.state.dateType
        }

        this.setState({
            params:value
        });
        axios.post('/api/statistics/car/charge/qry',{...value}).then(res => {
            if (res && res.data && res.data.length > 0) {
                //开始组建折线图信息
                this.setState({
                    tableData: res.data
                });
                var nameArr = new Array();
                var seriesArr = new Array();
                for (var i = 0; i < res.data.length; i++) {
                    var jsonObj = {};
                    nameArr.push(res.data[i].plateNo);
                    jsonObj['name'] = res.data[i].plateNo;
                    jsonObj['type'] = 'line';
                    jsonObj['data'] = res.data[i].data;
                    jsonObj['smooth'] = true;
                    seriesArr.push(jsonObj);
                }
                if (nameArr.length > 0) {
                    this.setState(Object.assign(this.state.lineOption, {legend: {'data': nameArr}, series: seriesArr}));
                }
            }
        });
    }


    userChargeInfo() {
        this.props.history.push('/data/userChargeReport');
    }

    carChargeInfo() {
        this.props.history.push('/data/carChargeReport');
    }


    render() {
        const token=(JSON.parse(sessionStorage.getItem("token"))||{}).token;
        let locale=sessionManager.get('locale');
        let exportQs=`${qs.stringify(this.state.params)}&token=${token}&locale=${locale}`;
        const common = this.props.intl.messages.common;
        return (
            <div>
                <div style={{marginTop: 20}}>
                    <Select placeholder={'报表类型'} defaultValue={this.state.dateType} onChange={this.selectValue}
                            style={{width: 140, marginRight: 20}}>
                        <Option value="1">年报表</Option>
                        <Option value="2">月报表</Option>
                        <Option value="4">自定义报表</Option>
                    </Select>
                    {this.state.dateType !== '4' &&
                    <YearSelect style={{float: 'left'}} changeYear={this.changeYear.bind(this)}/>}
                    {this.state.dateType === '2' &&
                    <MonthSelect style={{width: 100, marginRight: 20}} changeMonth={this.changeMonth.bind(this)}/>}
                    {this.state.dateType === '4' &&
                    <RangePicker allowClear={false} style={{marginRight: 20}} onChange={this.onChange}/>}
                    <Select defaultValue={this.state.showForm} style={{width: 100, marginRight: 20}}
                            optionLabelProp="children" onChange={this.handleChange}>
                        <Option value="1">折线图</Option>
                        <Option value="0">表格</Option>
                    </Select>
                    <Button type="primary" className="ant-btn-84" onClick={this.search}>{common.search}</Button>
                    <a href={`${axios.defaults.baseURL}/api/statistics/car/charge/export?${exportQs}`}>
                        <Button type="primary">导出报表</Button>
                    </a>
                    <br/><br/>
                    <span style={{textAlign: 'center', display: 'block'}}>{common.carChargeDetails}</span>
                    {this.state.showForm === '1' && <LineReact option={this.state.lineOption}/>}
                    {this.state.showForm === '0' &&
                    <Table dataSource={this.state.tableData[0].data?this.state.tableData:[]} scroll={{x: (this.state.tableData[0].dateList.length+2)*180}}
                           bordered size="middle" style={{marginTop: 20}}>
                        {this.state.tableData[0].data&& <Column
                            title="车牌号"
                            dataIndex="plateNo"
                            key="plateNo"
                            width={180}
                            align={'center'}
                        />}
                        {this.state.tableData[0].data&& this.state.tableData[0].dateList.map((k, v) => {
                            return <Column
                                title={k}
                                dataIndex={`data[${v}]`}
                                key={v}
                                width={180}
                                align={'center'}
                            />
                        })}
                        {this.state.tableData[0].data&& <Column
                            title="合计"
                            dataIndex="elecSum"
                            key="elecSum"
                            fixed="right"
                            width={180}
                            align={'center'}
                        />}
                    </Table>}
                </div>
            </div>
        );
    }
}

export default injectIntl(CarChargeReport);